package com.xuanzheng.company.servlet;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.xuanzheng.company.entity.User;
import com.xuanzheng.company.service.UserService;
import com.xuanzheng.company.service.impl.UserServiceImpl;
import com.xuanzheng.company.util.PasswordUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@WebServlet("/verifyPassword")
public class VerifyPasswordServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();
    private Gson gson = new Gson();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> result = new HashMap<>();
        
        // 获取当前登录用户
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            result.put("success", false);
            result.put("message", "请先登录");
            out.print(gson.toJson(result));
            return;
        }
        
        User currentUser = (User) session.getAttribute("user");
        
        try {
            // 读取请求体中的JSON数据
            BufferedReader reader = request.getReader();
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            
            // 解析JSON数据
            JsonObject jsonObject = gson.fromJson(sb.toString(), JsonObject.class);
            String password = jsonObject.get("password").getAsString();
            
            // 验证密码
            boolean isValid = PasswordUtil.verifyPassword(password, currentUser.getPassword());
            
            if (isValid) {
                result.put("success", true);
                result.put("message", "密码验证成功");
            } else {
                result.put("success", false);
                result.put("message", "密码错误");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.put("success", false);
            result.put("message", "密码验证失败: " + e.getMessage());
        }
        
        out.print(gson.toJson(result));
    }
} 